package com.example.mycomposelearing.dataobserval

import androidx.compose.runtime.*
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch

/**
 *@Author tgw
 *@Date 2023/07/06
 *@describe
 */
class MainViewModel : ViewModel() {
    val count = MutableLiveData<Int>(0)
    val countList = MutableLiveData<ArrayList<Int>>(arrayListOf(0, 1))

    // 状态数据初始化，初始化为空字符串,compose 独有的
    val composeCount = mutableStateOf<Int?>(0)

    // Create a flow that will emit whenever our person-specific greeting changes
    val snapshotFlow = snapshotFlow<Int> { 1 }
    val stateFlow = MutableStateFlow<Int>(value = -1)
    val sharedFlow = MutableSharedFlow<Int>()
    val sharedFlowCount = mutableStateOf<Int>(0)

    var inputMessage by mutableStateOf("")


    val suggestions: StateFlow<String> =
        snapshotFlow { inputMessage }.stateIn(
            scope = viewModelScope,
            //WhileSubscribed 策略是在没有订阅者的时候, 会取消上游的 Flow, 避免浪费资源.
            // 但是有时候视图层可能发生一些系统行为导致的配置发生变化.
            // 这里就会触发取消和重新订阅上游的 Flow.
            // 所以官方十分推荐使用 WhileSubscribed(5000) 的策略.
            // 表示 5 秒内如果都没有订阅者, 就取消, 这很好的避免了因为配置变化导致的资源浪费.
            started = SharingStarted.WhileSubscribed(5_000),
            initialValue = ""
        )


    fun add() {
        count.value = count.value?.plus(1)
    }


    fun addList(value: Int) {
        countList.value?.add(value)
    }

    fun composeCountAdd() {
        composeCount.value = (composeCount.value ?: 0).plus(1)
    }


    fun sendStateFlow(value: Int) {
        viewModelScope.launch {
            stateFlow.emit(value)
        }
    }


    fun sendSharedFlow(value: Int) {
        viewModelScope.launch {
            sharedFlow.emit(value)
        }
    }

    @Composable
    fun sendSnapshotFlow(value: Int) {
        snapshotFlow.collectAsState(initial = 1)
    }


    fun collectSharedFlow() {
        viewModelScope.launch {
            sharedFlow.collect {
                sharedFlowCount.value = it
                println("tgw2收集数据$it")
            }
        }
    }

    @Composable
    fun updateInputSuggestions(newInput: String) {
        inputMessage = newInput
        suggestions.collectAsState()
    }

}


